import socket
from connManager import *

#CONN_STATUS = enum(NONE=0, CONNECTED=1, CONNECTING=2, DISCONNECT=3)
NONE=0
CONNECTED=1
CONNECTING=2
DISCONNECT=3

class Conn():
	def __init__(self):
		self.fd = -1
		self.buffer = ""
		self.callback = None
		self.status = NONE
		self.isActive = 1
		self.conn = None

	def setAction(self, flag):
		self.isActive = flag;

	def connect(self, ip, port, callback = None):
		self.status = CONNECTING
		self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.fd = self.conn.fileno();
		if( self.conn == "" ):
			return -1
		self.conn.connect((ip, port))
		global_cm.addConn(self)
		self.conn.setblocking(0)
		if callback :
			self.callback = callback
		self.status = CONNECTED

	def close(self):
		self.conn.close()

	def send(self, buffer):
		self.conn.send(buffer)

	def recv(self):
		data = self.conn.recv(10240);
		buffer = self.buffer + data
		return buffer

	def recv_block(self):
		self.conn.setblocking(1)
		buffer = self.recv()
		self.conn.setblocking(0)
		return buffer

	def sendAndRecv_blocking(self, buffer):
		if buffer :
			self.send(buffer)
			buf = self.recv_block()
			return buf
		return ""





		

